<template>
  <div class="manage">
    <el-card class="search-top">
      <!-- 顶部操作栏 -->
      <div class="search-bar">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="80px">
          <el-row :gutter="10">
              <el-form-item label="角色名称" prop="keywords">
                <el-input
                    v-model="queryParams.role.description"
                    placeholder="角色名称"
                    clearable
                    style="width: 200px"
                    @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item label-width="80px" style="margin-left:25px">
                <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
                <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
              </el-form-item>
          </el-row>
        </el-form>
      </div>
    </el-card>


    <el-card shadow="never" class="search-table">
      <div class="flex-x-between mb-10px">
        <div>
          <el-button type="success" icon="plus" @click="handleOpenDialog('insert',undefined)">
            新增
          </el-button>
          <el-button type="danger" icon="Delete" @click="handleDelete()" :disabled="flag">
            删除
          </el-button>
        </div>
      </div>
      <!-- 菜单表格 -->
      <div class="common-table">
        <!-- 用户数据Table -->
        <el-table :data="tableData" @selection-change="handleSelectionChange" stripe style="width: 100%"
                 border max-height="300px" v-loading="loading">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column prop="description" label="角色名称" width="400" align="center"/>
          <el-table-column prop="roleType" label="角色编码" align="center" width="200"/>
          <el-table-column label="状态" align="center" width="80">
            <template #default="scope">
              <el-tag v-if="scope.row.status === '1'" type="success">正常</el-tag>
              <el-tag v-else type="danger">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="showOrder" label="排序" align="center" width="110px"/>
          <el-table-column fixed="right" align="center" label="操作" width="auto">
            <template #default="scope">
              <el-button
                  type="primary"
                  link
                  size="small"
                  icon="position"
                  @click.stop="powerDialog(scope.row.roleId)"
              >
                分配权限
              </el-button>
              <el-button
                  type="primary"
                  link
                  size="small"
                  icon="edit"
                  @click.stop="handleOpenDialog('edit',scope.row)"
              >
                编辑
              </el-button>
              <el-button
                  type="danger"
                  link
                  size="small"
                  icon="delete"
                  @click.stop="handleDelete(scope.row.roleId)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pager">
          <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 30, 40]"
              :small="small"
              :disabled="disabled"
              :background="background"
              layout="->,total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
    <!-- 添加菜单对话框 -->
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="45%"
        align-center
        @close="handleCloseDialog"
    >
      <el-form :disabled="disableFlag" ref="menuFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="description">
          <el-input v-model="formData.description" placeholder="请输入角色名称" clearable/>
        </el-form-item>

        <el-form-item label="角色编码" prop="roleType">
          <el-input v-model="formData.roleType" placeholder="请输入角色编码" clearable/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="'1'">正常</el-radio>
            <el-radio :value="'2'">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="showOrder">
          <el-input-number
              v-model="formData.showOrder"
              style="width: 100px"
              controls-position="right"
              :min="0"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!disableFlag" type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="deleteFlag" @close="deleteCloseDialog" center title="警告" style="width: 420px;height: 148px">
      <component class="icons" is="WarningFilled" style="width: 25px;height: 25px;color: #ff9a2e"/>
      <span> 确认删除角色?</span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="deleteSubmit">确 定</el-button>
          <el-button @click="deleteFlag = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer
        v-model="assignPermDialogVisible"
        title="权限分配"
        size="50%"
    >
      <div class="flex-x-between">
        <el-input v-model="permKeywords" clearable class="w-[150px]"
                  style="width: 500px; margin-bottom: 10px"
                  placeholder="菜单权限名称">
        </el-input>
      </div>

      <el-tree
          ref="permTreeRef"
          node-key="value"
          show-checkbox
          :data="menuPermOptions"
          :filter-node-method="handlePermFilter"
          :default-expand-all="true"
          :check-strictly="false"
          class="mt-5"
      >
        <template #default="{ data }">
          {{ data.label }}
        </template>
      </el-tree>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleAssignPermSubmit">确 定</el-button>
          <el-button @click="assignPermDialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script setup>
import UploadUser from "@/components/icons/UploadUser.vue";
import {ref, reactive, computed, onMounted, watch} from 'vue';
import { Plus } from '@element-plus/icons-vue'
import {
  assignPermission,
  deleteByMenuId, deleteRoles,
  deleteUser, downloadTemp, exportUserInfo,
  getAllMenu, getAllMenuIdByRoleId,
  getMenuById, getRoleByPage,
  getUserByPage, insertRole, insertUser,
  resetUserPassword, updateRole,
  updateUser
} from "@/api/index.js";
import {ElMessage} from "element-plus";
import IconsSelect from "@/components/icons/iconsSelect.vue";
import axios from "axios";
import {getToken} from "@/utils/cookies.js";
import http from "@/utils/request.js";

const assignPermDialogVisible = ref(false);
const menuPermOptions = ref([]);
const permTreeRef =ref();
const permKeywords = ref("");

// 模拟菜单数据
const tableData = ref([]);

const loading = ref(false);
// 搜索关键字
const searchKey = ref('');
// 当前页码
const currentPage = ref(1);
// 每页条数
const pageSize = ref(10);
const small = ref(false)
const background = ref(true)
const disabled = ref(false)
const total = ref(0);
const disableFlag = ref(false);
const menuFormRef = ref(null);
const flag = ref(true);
const deleteRoleId = ref();
const deleteFlag = ref(false);
const roleIdTmp = ref();
// 初始菜单表单数据
const initialMenuFormData = ref({
  description: null,
  roleType: null,
  status: '1',
  showOrder: 0
});

const rules = reactive({
  description: [{required: true, message: "请输入角色名称", trigger: "blur"}],
  roleType: [{required: true, message: "请输入角色编码", trigger: "blur"}],
  status: [{required: true, message: "请选择显示状态", trigger: "change"}],
});

const formData = ref({...initialMenuFormData.value});

// 存储选中项的 id 数组
const selectIds = ref([]);
const dialog = reactive({
  title: '编辑菜单',
  visible: false,
  type: 'edit'
});

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  role: {
    description: null,
  }
});

watch(permKeywords, (val) => {
  permTreeRef.value.filter(val);
});
// 处理每页条数变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  queryParams.pageSize = pageSize.value;
  handleQuery();
};

// 处理当前页码变化
const handleCurrentChange = (newPage) => {
  console.log(newPage)
  currentPage.value = newPage;
  queryParams.pageNum = currentPage.value;
  console.log(queryParams.pageNum)
  handleQuery();
};

const handleQuery = () => {
  console.log('搜索');
  getRoleByPage(queryParams).then((data) => {
    if (data.data.code === 200) {
      console.log(data.data.data)
      tableData.value = data.data.data.records;
      console.log(tableData.value)
      total.value = data.data.data.total;
    } else {
      ElMessage.error(data.data.msg);
    }
  }).catch(() => {
    ElMessage.error("执行异常")
  }).finally(() => {
    loading.value = false;
  });
};



onMounted(() => {
  handleQuery();
})


const handleResetQuery = () => {
  queryParams.pageNum = 1;
  queryParams.pageSize = 10;
  queryParams.role.description = null;
  pageSize.value = 10;
  currentPage.value = 1;
  handleQuery();
}

const handleCloseDialog = () => {
  resetForm();
  disableFlag.value = false;
  dialog.visible = false;
};

const resetForm = () => {
  // menuFormRef.value.resetFields();
  menuFormRef.value.clearValidate();
  formData.value = {
    description: null,
    roleType: null,
    status: '1',
    showOrder: 0
  };
};
const importFormData = {
  files: []
};

const handleOpenDialog = (type, row) => {
  if (type === 'edit') {
    dialog.visible = true;
    dialog.title = "编辑角色"
    dialog.type = "edit"
    initialMenuFormData.value = {...row};
    formData.value = {...row};
  } else if (type === 'insert') {
    dialog.visible = true;
    dialog.title = "新增角色"
    dialog.type = "insert"
  }
};

const handleSubmit = async () => {
  if (!menuFormRef.value) return;
  try {
    // 进行表单验证
    const valid = await menuFormRef.value.validate();
    if (valid) {
      // 表单验证通过，调用 updateUser 方法更新用户信息
      let data;
      if (dialog.type === "insert") {
        data = await insertRole(formData.value);
      } else if (dialog.type === "edit") {
        data = await updateRole(formData.value);
      }
      if (data && data.data.code === 200) {
        // 更新成功，给出成功提示，关闭对话框并重新查询数据
        ElMessage.success(data.data.msg);
        handleCloseDialog();
        handleQuery();
      } else {
        // 更新失败，给出失败提示
        ElMessage.error(data.data.msg);
      }
    } else {
      // 表单验证失败，输出日志
      console.log("表单校验失败");
    }
  } catch (error) {
    // 捕获并输出详细的错误信息，给出通用错误提示
    console.error("执行提交操作时出现错误:", error);
    ElMessage.error("执行异常");
  }
};

const handleDelete = (roleId) => {
  deleteRoleId.value = [roleId || selectIds.value].join(",")
  console.log(deleteRoleId.value)
  deleteFlag.value = true;
};

const deleteCloseDialog = () => {
  deleteRoleId.value = null;
  deleteFlag.value = false;
}

const deleteSubmit = () => {
  deleteRoles(deleteRoleId.value).then((data) => {
    if (data.data.code === 200) {
      ElMessage.success(data.data.msg);
      deleteCloseDialog();
      handleQuery()
    } else {
      ElMessage.error(data.data.msg);
    }
  }).catch(() => {
    ElMessage.error("执行异常")
  })
}


const handleSelectionChange = (selection) => {
  selectIds.value = selection.map((item) => item.roleId);
  flag.value = selectIds.value.length === 0;
  console.log('选中项的 ID:', selectIds.value);
};

const powerDialog = async (roleId) => {
  try {
    roleIdTmp.value = roleId;
    assignPermDialogVisible.value = true;
    const data = await getAllMenu();
    if (data.data.code === 200) {
      menuPermOptions.value = convert(data.data.data);
    } else {
      ElMessage.error(data.data.msg);
    }

    const data2 = await getAllMenuIdByRoleId(roleId);
    data2.data.data.forEach((menu) => {
      permTreeRef.value.setChecked(menu.menu_id, true, false);
    });

  }catch (error) {
    // 捕获并输出详细的错误信息，给出通用错误提示
    console.error("执行提交操作时出现错误:", error);
    ElMessage.error("执行异常");
  }
}

const handleAssignPermSubmit = () => {
  console.log(roleIdTmp.value);
  const checkedMenuIds = permTreeRef.value.getCheckedNodes(false, true).map(function (node) {
    return node.value;
  });
  const param = {
    roleId: roleIdTmp.value,
    menuIds: checkedMenuIds
  }
  assignPermission(param).then((data) => {
    if (data.data.code === 200) {
      ElMessage.success(data.data.msg);
      assignPermDialogVisible.value = false;
    } else {
      ElMessage.error(data.data.msg);
    }
  }).catch(() => {
    ElMessage.error("执行异常")
  })
}



function convert(arr) {
  return arr.map(item => {
    const newItem = {
      ...item,
      label: item.menuName,
      value: item.menuId
    };
    delete newItem.menuName;
    delete newItem.menuId;

    if (item.children) {
      newItem.children = convert(item.children);
    }
    return newItem;
  });
}
function handlePermFilter(value, data) {
  if (!value) {
    return true;
  }
  return data.label.includes(value);
}
</script>




<style scoped>
.manage {
  height: 80%;

  .search-table {
    box-shadow: var(--el-box-shadow-light);
  }

  .manage-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .common-table {
    height: 80%;
    position: relative;
    margin-top: 10px;

    .pager {
      position: relative;
      top: 10px;
      bottom: 0;
    }
  }
}


.search-top {
  margin-bottom: 10px;
}

.flex-x-between {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>